import { useEditStudentInfo, useGetStudentInfo } from '@/services/student';
import {
  Button,
  Drawer, Form, Input, Space, Spin,
} from 'antd';
import UploadImage from '@/components/OSSImageUpload';
import { useMemo } from 'react';

/**
* 编辑学员信息
*/
interface IProps {
  id:string,
  show:boolean,
  onChangeShow:() => void
}
const EditStudent = ({ id, show, onChangeShow }:IProps) => {
  const [form] = Form.useForm();
  const { data, loading } = useGetStudentInfo(id);
  const [editHandler, editLoading] = useEditStudentInfo();
  const initValue = useMemo<any>(() => {
    form.setFieldsValue(data ? {
      ...data,
      avatar: [{ url: data.avatar ? data.avatar : null }],
    } : {});
  }, [data]);
  const onSubmitHandler = async () => {
    const values = await form.validateFields();
    if (values) {
      delete values.password;
      const newValues = {
        ...values,
        avatar: values.avatar[0].url,
      };
      editHandler(id, newValues, onChangeShow);
    }
  };
  return (
    <Drawer
      title="编辑学员信息"
      onClose={onChangeShow}
      open={show}
      extra={(
        <Space>
          <Button onClick={onChangeShow}>取消</Button>
          <Button type="primary" loading={editLoading} onClick={onSubmitHandler}>提交</Button>
        </Space>
      )}
    >
      <Spin spinning={loading}>
        <Form
          form={form}
          initialValues={initValue}
          labelCol={{ span: 4 }}
          wrapperCol={{ span: 14 }}
          layout="horizontal"
          style={{ maxWidth: 600 }}
        >
          <Form.Item label="昵称：" name="name">
            <Input />
          </Form.Item>
          <Form.Item label="电话：" name="tel">
            <Input />
          </Form.Item>
          <Form.Item label="账号：" name="account">
            <Input />
          </Form.Item>
          <Form.Item label="密码：" name="password">
            <Input disabled type="password" />
          </Form.Item>
          <Form.Item label="头像" name="avatar">
            <UploadImage maxCount={1} />
          </Form.Item>
        </Form>
      </Spin>
    </Drawer>
  );
};

export default EditStudent;
